<template>
	<view class="app">
		<!-- 页面内容开始 -->
		<view class="list-page">

			<!--头部开始 -->
			<view class="list-head">
				<view class="list-search">
					<view class="list-search-input">
						<!-- 快捷搜索 -->
						<u-search v-model="queryForm1.formData[listSearch.key]" :placeholder="listSearch.placeholder" :show-action="false" input-align="center" class="search-input" shape="square" @search="search" @clear="search"></u-search>
						<!-- 高级搜索按钮图标 -->
						<u-icon class="advanced-search" name="list-dot" color="#909399" size="40" @click="show.advancedSearch = true" ></u-icon>
					</view>
					<!-- 状态筛选 -->
					<view class="subsection" v-show="!queryForm1.formData.inviter_id">
						<u-subsection :list="subsection1.list" :current="subsection1.current" :button-color="subsection1.list[subsection1.current].color"
							active-color="#ffffff" bg-color="#ffffff" @change="sectionChange1"></u-subsection>
					</view>
				</view>
				<!-- 总记录数 -->
				<view class="total-desc" style="display: flex;align-items: center;">
					<view style="flex: 1;"> 共 <text class="total-num">{{ data.total }}</text> 条记录 </view>
					<view @click="sortFn">{{ sortText }}排序</view>
				</view>
			</view>
			<!--头部结束 -->

			<!--无内容时 -->
			<view v-if="data.list.length == 0" style="padding: 40% 0 80% 0;">
				<u-empty v-if="loading" text="查询中..." mode="search"></u-empty>
				<u-empty v-else text="暂无内容" mode="list"></u-empty>
			</view>
			<!--有内容时开始-->
			<view v-else class="list-main">
				<block v-for="(item, index) in data.list" :key="item._id">
					<!-- ****************** 自定义item的内容开始 ****************** -->

					<view class="list-item">
						<view class="content" @click.stop="collapse(index)">
							<view class="left">
								<u-image width="160" height="160" mode="aspectFill" :src="item.avatar" border-radius="8"></u-image>
							</view>
							<view class="right">
								<view class="first-child"> {{ nameFn(item) }} </view>
								<view>手机号码：{{ $fn.hidden($getData(item, 'social_info.mobile'),3,4) || '未填写' }}</view>
								<view v-if="$getData(item, 'fx.original_share_user') && $getData(item, 'fx.original_share_user._id') !== $getData(item, 'inviter_uid.0')">邀请人是：{{ $getData(item, 'fx.original_share_user.nickname') }}（粉丝）</view>
								<view>邀请时间：{{ $fn.timeFormat(item.invite_time) }}</view>
								<view>用户余额：¥ {{ $fn.priceFilter($fn.getData(item,"account_balance.balance",0)) }}</view>
								<view>累计消费：¥ {{ $fn.priceFilter($fn.getData(item,"account_per.my_payment",0)) }}</view>
								<view>用户会员等级：{{ vipLvNameFn(item) }}</view>
								<view>用户分销等级：{{ fxLvNameFn(item) }}</view>
								<view>最新登录时间：{{ $fn.timeFormat(item.last_login_date) || "从未登录" }}</view>
								<!-- <u-icon class="setting" name="setting" color="#909399" size="36"></u-icon> -->
							</view>
						</view>
						<view class="collapse" :class="footer.actived === index ? 'actived' : 'actived'">
							<block v-for="(btn, btnIndex) in footer.list" :key="btnIndex">
								<view v-if="footerShowFn(btn, item, index)" @click="footerBtn(item, btn, index)" :class="btn.main ? 'main':''">
									{{ btn.text }}
								</view>
							</block>
						</view>
					</view>

					<!-- ****************** 自定义item的内容结束 ****************** -->
				</block>
				<!-- 加载更多-->
				<u-loadmore :status="state.loadmore" bg-color="var(--bgcolor)" margin-bottom="30" @loadmore="nextPage" />
			</view>
			<!--有内容时结束-->
		</view>

		<!-- 高级搜索弹窗开始 -->
		<u-popup v-model="show.advancedSearch" mode="top" closeable>
			<view class="search-popup">
				<scroll-view scroll-y="true" class="scroll-view">
					<view>
						<!-- ****************** 自定义高级搜索表单开始 ****************** -->
						<u-form
							:model="queryForm1.formData"
							ref="queryForm1"
							label-position="top"
							:label-style="{ fontWeight: '500' }"
						>
							<u-form-item label="邀请时间" prop="_add_time">
								<view class="date-range" @click="show._add_time = true">
									{{ queryForm1.formData._add_time[0] ? $fn.timeFormat(queryForm1.formData._add_time[0], "yyyy/MM/dd") + " - " + $fn.timeFormat(queryForm1.formData._add_time[1], "yyyy/MM/dd") : "日期范围" }}
								</view>
							</u-form-item>
							<u-form-item label="姓名" prop="real_name">
								<u-input v-model="queryForm1.formData.real_name" />
							</u-form-item>
							<u-form-item label="昵称" prop="nickname">
								<u-input v-model="queryForm1.formData.nickname" />
							</u-form-item>
							<u-form-item label="手机号" prop="mobile">
								<u-input v-model="queryForm1.formData.mobile" />
							</u-form-item>
						</u-form>
						<!-- 日历范围选择组件 -->
						<u-calendar
							v-model="show._add_time"
							mode="range"
							safe-area-inset-bottom
							btn-type="default"
							active-bg-color="var(--main)"
							range-bg-color="var(--secondary)"
							@change="calendarChange"
						></u-calendar>
						<!-- ****************** 自定义高级搜索表单结束 ****************** -->
					</view>
				</scroll-view>
				<view class="footer-btn">
					<view class="btn reset" @click="advancedSearchReset">重 置</view>
					<view class="btn confirm" @click="advancedSearchConfirm">确 定</view>
				</view>
			</view>
		</u-popup>
		<!-- 高级搜索弹窗结束 -->

		<!-- 页面内容结束 -->
		<!-- 全局公共浮球导航模块 -->
		<vk-data-float-ball :scroll-top="scrollTop"></vk-data-float-ball>
	</view>
</template>

<script>
var vk = uni.vk;			// vk依赖
var originalForms = {}; // 表单初始化数据
export default {
	data() {
		// 页面数据变量
		return {
			// 获取list数据的云函数请求路径
			url: "client/salesman.getUserList",
			// init请求返回的数据
			data: {
				list: [],
				total: "-",
				hasMore: true // 是否还有下一页数据
			},
			// 列表查询请求数据
			queryForm1: {
				// 分页数据
				pagination: {
					pageIndex: 1, //当前页码
					pageSize: 20 //每页显示数量
				},
				// 查询表单数据源，可在此设置默认值
				formData: {
					_add_time: [],
					mobile: "",
					real_name: "",
					type: 0,
					inviter_id:""
				},
				// 查询匹配规则 fieldName:指定数据库字段名,不填默认等于key
				columns: [
					{ key: "_add_time", title: "邀请时间", type: "datetimerange", width: 320, mode: "[]", fieldName: "invite_time" },
					{ key: "mobile", title: "手机号", type: "text", width: 200, mode: "%%", fieldName: "social_info.mobile" },
					{ key: "real_name", title: "姓名", type: "text", width: 200, mode: "%%", fieldName: "fx.real_name" },
					{ key: "nickname", title: "昵称", type: "text", width: 200, mode: "%%" },
				],
				// 排序规则
				sortRule: [
					{ name:"invite_time", type:"desc" }, // desc降序 asc升序
				]
			},
			// 列表搜索框 key 可以是 queryForm1.columns 中的任意1个key
			listSearch: { key: "mobile", placeholder: "输入手机号搜索" },
			// 页面状态
			state: {
				loadmore: "loading", // loadmore的显示状态
			},
			// 头部状态选择
			subsection1: {
				key: "type", // 查询字段名
				current: 0, // 当前选中的索引
				list: [
					{ name: "直推", value: 0, color: "var(--main)" },
					{ name: "间推", value: 1, color: "var(--main)" },
				]
			},
			// 每一项底部的拓展按钮
			footer: {
				actived: "",
				color: "#909399",
				list: [
					{
						text: "Ta的粉丝",
						click(item) {
							vk.navigateTo(`../user-list/user-list?inviter_id=${item._id}`);
						},
						main: true, // 颜色高亮显示
						// 显示规则
						showRule:(item, index) => {
							return this.queryForm1.formData.type === 0 && !this.queryForm1.formData.inviter_id ? true : false;
						},
					},
					{
						text: "查看详情",
						click(item) {
							vk.navigateTo(`./user-detail?_id=${item._id}`);
						},
						// 显示规则
						showRule:(item, index) => {
							return this.queryForm1.formData.type === 0 && !this.queryForm1.formData.inviter_id ? true : false;
						}
					},
					{
						text: "拨打电话",
						// 点击事件
						click(item) {
							uni.makePhoneCall({
								phoneNumber: item.social_info.mobile
							});
						},
						// 显示规则
						showRule(item, index) {
							return vk.pubfn.getData(item,"social_info.mobile") ? true : false;
						},
					},
					{
						text: "添加微信",
						click(item) {
							let weixin_no = vk.pubfn.getData(item, "social_info.weixin_no");
							let weixin_qrcode = vk.pubfn.getData(item, "social_info.weixin_qrcode");
							if (weixin_qrcode) {
								uni.previewImage({
									urls:[weixin_qrcode]
								});
							} else if (weixin_no) {
								uni.setClipboardData({
									data: item.social_info.weixin_no,
									success() {
										vk.alert("微信号复制成功\n请前往微信添加好友！");
									}
								});
							}
						},
						// 显示规则
						showRule(item, index) {
							return vk.pubfn.getData(item,"social_info.weixin_no") || vk.pubfn.getData(item,"social_info.weixin_qrcode") ? true : false;
						},
					},
				]
			},
			// 页面上所有弹窗的开关
			show: {
				_add_time: false, // 高级搜索弹窗中的日历选择弹窗开关
				advancedSearch: false, // 高级搜索弹窗开关
			},
			sortText: "",
			loading: false, // 是否请求中
			scrollTop: 0, // 滚动条当前位置
		};
	},
	onPageScroll(e) {
		this.scrollTop = e.scrollTop;
	},
	// 监听 - 页面每次【加载时】执行(如：前进)
	onLoad(options = {}) {
		vk = uni.vk;
		this.options = options;
		this.init(options);
	},
	// 监听 - 页面【首次渲染完成时】执行。注意如果渲染速度快，会在页面进入动画完成前触发
	onReady() {

	},
	// 监听 - 页面每次【显示时】执行(如：前进和返回) (页面每次出现在屏幕上都触发，包括从下级页面点返回露出当前页面)
	onShow() {},
	// 监听 - 页面每次【隐藏时】执行(如：返回)
	onHide() {},
	// 监听 - 页面每次【卸载时】（一般用于取消页面上的监听器）
	onUnload(){},
	// 监听 - 页面下拉刷新
	onPullDownRefresh() {
		setTimeout(() => {
			uni.stopPullDownRefresh();
		}, 1000);
	},
	// 监听 - 页面触底部
	onReachBottom() {
		this.nextPage();
	},
	// 函数
	methods: {
		// 页面数据初始化函数
		init(options) {
			let that = this;
			console.log("init: ", options);
			// 拷贝一份表单的初始值
			originalForms["queryForm1"] = vk.pubfn.copyObject(that.queryForm1.formData);

			// 根据url参数status，设置当前选中的状态
			if (options.type) {
				let index = vk.pubfn.getListIndex(that.subsection1.list, "value", Number(options.type));
				that.sectionChange1(index, false);
			}

			if (options.time) {
				let { todayStart, todayEnd } = vk.pubfn.getCommonTime();
				that.queryForm1.formData._add_time = [todayStart,todayEnd];
			}

			if (options.inviter_id) {
				that.queryForm1.formData.inviter_id = options.inviter_id;
			}

			// 查询
			that.search();
		},
		// 搜索查询
		search(e) {
			let that = this;
			that.data.list = [];
			that.queryForm1.pagination.pageIndex = 1;
			that.data.pageKey = true;
			that.getList();
		},
		// 加载下一页数据
		nextPage() {
			let that = this;
			if (that.state.loadmore == "loadmore") {
				that.state.loadmore = "loading";
				that.queryForm1.pagination.pageIndex++;
				that.getList();
			}
		},
		// 获取list数据
		getList(obj = {}) {
			let that = this;
			vk.pubfn.getListData2({
				that: that,
				url: that.url,
				success: obj.success
			});
		},
		// 顶部选项改变事件
		sectionChange1(index, search=true) {
			let that = this;
			if (index < 0) {
				return false;
			}
			that.subsection1.current = index;
			let key = that.subsection1.key;
			let value = that.subsection1.list[index].value;
			that.$set(that.queryForm1.formData, key, value);
			that.data.list = [];
			that.data.total = "-";
			// 搜索
			if (search) that.search();
		},
		// 高级搜索 - 确定按钮
		advancedSearchConfirm() {
			let that = this;
			that.show.advancedSearch = false;
			that.search();
		},
		// 高级搜索 - 重置按钮
		advancedSearchReset() {
			let that = this;
			that.queryForm1.formData = vk.pubfn.copyObject(originalForms["queryForm1"]);
			that.search();
		},
		// 折叠开关
		collapse(index) {
			let that = this;
			that.footer.actived = that.footer.actived !== index ? index : "";
		},
		// 底部按钮显示判断
		footerShowFn(btn, item, index) {
			let that = this;
			if (typeof btn.showRule == "function") {
				return btn.showRule(item, index);
			} else {
				return true;
			}
		},
		// 折叠打开后的底部按钮点击事件
		footerBtn(item, btn, index) {
			if (typeof btn.click === "function") {
				btn.click(item, btn, index);
			}
		},
		// 监听 - 日历组件的change事件
		calendarChange(e) {
			let that = this;
			that.$set(that.queryForm1.formData, "_add_time", [
				vk.pubfn.toTimeLong(e.startDate + " 00:00:00"),
				vk.pubfn.toTimeLong(e.endDate + " 23:59:59")
			]);
		},
		nameFn(userInfo){
			return vk.myfn.salesman.getName(userInfo);
		},
		sortFn(){
			let that = this;
			let sortList = [
				{ title: "累计消费从大到小（降序）", sortRule: [{ name:"account_per.my_payment", type:"desc" }] },
				{ title: "用户余额从大到小（降序）", sortRule: [{ name:"account_balance.balance", type:"desc" }] },
				{ title: "邀请时间从晚到早（降序）", sortRule: [{ name:"invite_time", type:"desc" }] },
				{ title: "累计消费从小到大（升序）", sortRule: [{ name:"account_per.my_payment", type:"asc" }] },
				{ title: "用户余额从小到大（升序）", sortRule: [{ name:"account_balance.balance", type:"asc" }] },
				{ title: "邀请时间从早到晚（升序）", sortRule: [{ name:"invite_time", type:"asc" }] }
			];
			let list = sortList.map((item, index) => {
				return item.title;
			});
			vk.showActionSheet({
				title: "",
				list,
				color: "#000000",
				success: (res) => {
					let item = sortList[res.index];
					that.queryForm1.sortRule = item.sortRule;
					that.sortText = item.title;
					that.search();
				}
			});
		},
		vipLvNameFn(userInfo={}){
			try {
				let vip_level_rule = vk.getVuex('$user.mchInfo.vip_level_rule');
				let { vip_lv: lv } = userInfo;
				let item = vk.pubfn.getListItem(vip_level_rule, "lv", lv) || {};
				return item.name;
			} catch(err){
				return "未知";
			}
		},
		fxLvNameFn(userInfo={}){
			try {
				let is_fx = vk.pubfn.getData(userInfo, "fx.is_fx");
				if (is_fx) {
					let lv = vk.pubfn.getData(userInfo, "fx.lv");
					let level_rule = vk.getVuex('$user.mchInfo.fx.level_rule');
					let item = vk.pubfn.getListItem(level_rule, "lv", lv);
					return item.name;
				} else {
					return "未申请推广大使";
				}
			} catch(err){
				return "未知";
			}
		}
	},
	// 计算属性
	computed: {}
};
</script>
<style lang="scss" scoped>
.app{
	background-color: var(--bgcolor);
	min-height: calc(100vh - var(--window-top));
}

/* list主结构开始 */
.list-page {
	background-color: var(--bgcolor);

	/* 头部 */
	.list-head {
		.total-desc {
			font-size: 28rpx;
			color: #999;
			padding: 20rpx 30rpx 0rpx 30rpx;
			padding-bottom: 0;
			line-height: 52rpx;
			width: 100%;
		}

		.total-num {
			font-weight: bold;
			color: black;
			font-size: 26rpx;
			margin-left: 10rpx;
			margin-right: 10rpx;
		}

		.list-search {
			background-color: #ffffff;
			padding: 20rpx 30rpx;

			.subsection {
				margin-top: 20rpx;
			}

			.list-search-input {
				display: flex;

				.search-input {
					flex: 1;
				}

				.advanced-search {
					margin-left: 20rpx;
				}
			}
		}
	}

	.list-main {
		padding: 0rpx 0rpx 20rpx 0rpx;
	}

}

/* list主结构结束 */

/* 高级搜索弹窗开始 */
.search-popup {
	background-color: #f3f3f3;

	.scroll-view {
		flex: 1;
		height: 1024rpx;
		padding: 0;
	}

	.footer-btn {
		display: flex;
		.btn {
			flex: 1;
			display: block;
			text-align: center;
			line-height: 80rpx;
		}
		.btn:active {
			opacity: 0.7;
		}
		.reset {
			color: #404040;
			background-color: #ffffff;
		}
		.confirm {
			background-color: var(--main);
			color: #ffffff;
		}
	}

	::v-deep .u-form-item {
		background-color: #ffffff;
		display: block;
		padding: 20rpx;
		color: #7e7e7e;
		padding-top: 6rpx;
		color: #262626;
		margin-bottom: 20rpx;
	}

	.date-range {
		text-align: center;
		background-color: #f6f6f6;
		line-height: 60rpx;
		border-radius: 30rpx;
		color: #7f7f7f;
		width: 100%;
	}
}
/* 高级搜索弹窗结束 */

/* list-item开始 */
.list-item {
	margin: 20rpx;

	>.content {
		display: flex;
		background-color: #ffffff;
		padding: 20rpx;
		color: #606266;

		.mt10{
			margin-top: 10rpx;
		}

		.text-one {
			display: -webkit-box;
			-webkit-box-orient: vertical;
			-webkit-line-clamp: 1;
			overflow: hidden;
		}

		>.left{
			display: flex;
			align-items: center;
			margin-right: 20rpx;
		}

		>.right {
			flex: 1;
			font-size: 24rpx;
			position: relative;

			>view{
				margin-top: 10rpx;
				display: -webkit-box;
				-webkit-box-orient: vertical;
				-webkit-line-clamp: 1;
				overflow: hidden;
			}

			.first-child{
				margin-top: 0;
			}

			.setting {
				position: absolute;
				right: 0rpx;
				top: 0rpx;
				margin: 0;
			}
		}
	}

	.collapse {
		display: none;
		padding: 20rpx;
		font-size: 24rpx;
		color: #909399;
		line-height: 40rpx;
		background-color: #ffffff;
		border-top: 1px solid #f8f8fa;

		grid-template-columns: repeat(4, 1fr);
		gap: 16rpx;
		box-sizing: border-box;
		direction: rtl; //反向填充

		>view {
			border: 2rpx solid #909399;
			border-radius: 20rpx;
			text-align: center;
			padding: 2rpx 10rpx;
			color: #909399;
		}
		>view.main {
			border: 2rpx solid var(--main);
			color: var(--main);
		}
	}

	.collapse.actived {
		display: grid;
	}
}
/* list-item结束 */


</style>
